<template>
  <div :id="id" :class="className" :style="{ height, width }"/>
</template>

<script setup lang="ts">
import {ref, onMounted} from "vue";
import * as echarts from 'echarts';

const props = defineProps({
  id: {
    type: String,
    default: "pie2Echarts",
  },
  className: {
    type: String,
    default: "",
  },
  width: {
    type: String,
    default: "100%",
    required: true,
  },
  height: {
    type: String,
    default: "220px",
    required: true,
  },
});


const chart: Ref<echarts.ECharts | null> = ref(null);

/** 设置图表  */
const setChartOptions = (data: any) => {
  if (!chart.value) {
    return;
  }
  const options =  {
    tooltip: {
      trigger: 'item'
    },
    legend: {
      bottom: 0,
      textStyle: {
        color: "#ffffff"
      },
    },
    series: [
      {
        name: '销售渠道',
        type: 'pie',
        radius: ['40%', '70%'],
        avoidLabelOverlap: false,
        padAngle: 5,
        itemStyle: {
          borderRadius: 10,
        },
        label: {
          show: false,
          position: 'center'
        },
        emphasis: {
          label: {
            show: true,
            fontSize: 40,
            fontWeight: 'bold'
          }
        },
        labelLine: {
          show: false
        },
        data: [
          { value: 1048, name: '客户直接下单' },
          { value: 735, name: '商户采购' },
        ]
      }
    ]
  };
  chart.value.setOption(options);
};

// 窗口大小变化时，重置图表大小
const handleResize = () => {
  setTimeout(() => {
    if (chart.value) {
      chart.value.resize();
    }
  }, 100);
};

onMounted(() => {
  chart.value = markRaw(echarts.init(document.getElementById(props.id) as HTMLDivElement));
  setChartOptions();
  window.addEventListener("resize", handleResize);
})
</script>

<style scoped>

</style>
